<?
/**
 * 数据库连接管理器
 * @author wudi
 *
 */
class doom_model_mysqliconnmgr {

    public static $connections = array();

    /**
     * 取数据库连接
     * @param array $config
     *      array('host' => 'localhost', 
                  'username' => 'root', 
                  'password' => '111111', 
                  'database' => 'cntv_uc', 
                  'charset' => 'UTF8')
     */
    static public function get($config) {

        $connKey = self::config2connKey($config);
        $conn = self::$connections[$connKey];
        
        if ($conn == NULL) {
            if (($conn = mysql_connect($config['host'], $config['username'], $config['password'], $config['database'])) == FALSE || mysql_select_db($config['database'], $conn) == FALSE || ($config['charset'] && (mysql_query("SET NAMES {$config['charset']}", $conn) == FALSE))) {
                //TODO
                //self::$error->add(mysql_errno() , mysql_error(), __METHOD__, __LINE__);
                return FALSE;
            }
            self::$connections[$connKey] = $conn;
        
        }
        return $conn;
    }

    /**
     * 关闭数据库连接
     * @param array/resource $conn 数据库配置/连接resource
     */
    static public function close($conn) {

        if (is_array($conn)) {
            $config = $conn;
            $connKey = self::config2connKey($config);
            if (($conn = self::$connections[$connKey]) != NULL && is_resource($conn)) {
                
                if (mysql_close($conn)) {
                    unset(self::$connections[$connKey]);
                    return TRUE;
                } else {
                    return FALSE;
                }
            } else {
                return TRUE;
            }
        } else if (is_resource($conn)) {
            $connKey = array_search($conn, self::$connections);
            if (mysql_close($conn)) {
                unset(self::$connections[$connKey]);
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            //TODO
            //self::$error->add(mysql_errno() , 'bad argument', __METHOD__);
            return FALSE;
        }
    }

    /**
     * 关闭所有连接
     */
    static public function closeAll() {

        foreach (self::$connections as $connKey => $connection) {
            if (is_resource($connection)) {
                if (mysql_close($connection)) {
                    unset(self::$connections[$connKey]);
                }
            }
        }
    }

    static private function config2connKey($config) {

        return $config['host'] . '_' . $config['database'];
    }
}

/**
 * 数据库操作类，提供基础CRUD方法
 * @author wudi
 * 
 */
class doom_model_mysqli {

    public $config = NULL;

    private $connection = NULL;

    /**
     * 默认构造器
     * @param array $config 数据库配置
     */
    public function __construct($config) {

        $this->config = $config;
        register_shutdown_function(array(&$this, 'close'));
    }

    /**
     * 进行数据库连接，如果已连接，则不做任何操作
     * @return true/false
     */
    private function getConnection() {

        if ($this->connection === NULL) {
            $conn = doom_model_mysqliconnmgr::get($this->config);
            if ($conn === FALSE) {
                //TODO
                //$this->error->add(1, '连接出错.', __MOETHOD__, __LINE__);
                return FALSE;
            }
            $this->connection = $conn;
        }
        return TRUE;
    }

    /**
     * 查询
     * @param string $sql
     * @param string $rsType 返回结果集类型(object/array/resource/assoc),默认为assoc 
     * @return array
     */
    public function query($sql, $rsType = NULL) {

        if ($this->getConnection() === FALSE) {
            return FALSE;
        }
        $rs = mysql_query($sql, $this->connection);
        if ($rs === FALSE) {
            //TODO
            //$this->error->add(mysql_errno($this->connection), mysql_error($this->connection), __METHOD__, __LINE__);
            return FALSE;
        }
        switch ($rsType) {
            case 'object':
                $result = array();
                while ($o = mysql_fetch_object($rs)) {
                    $result[] = $o;
                }
                break;
            case 'array':
                $result = array();
                while ($a = mysql_fetch_array($rs)) {
                    $result[] = $a;
                }
                break;
            case 'resource':
                $result = $rs;
                break;
            case 'assoc':
            default:
                $result = array();
                while ($a = mysql_fetch_assoc($rs)) {
                    $result[] = $a;
                }
                break;
        }
        return $result;
    }

    /**
     * 插入
     * @param $sql
     * @return string insert_id
     */
    public function insert($sql) {

        if ($this->getConnection() === FALSE) {
            return FALSE;
        }
        if (mysql_query($sql, $this->connection) === FALSE) {
            //TODO
            //$this->error->add(mysql_errno($this->connection), mysql_error($this->connection), __METHOD__, __LINE__);
            return FALSE;
        }
        return mysql_insert_id($this->connection);
    }

    /**
     * 更新
     * @param $sql
     * @return int 影响行数
     */
    public function update($sql) {

        if ($this->getConnection() === FALSE) {
            return FALSE;
        }
        if (mysql_query($sql, $this->connection) === FALSE) {
            //TODO
            //$this->error->add(mysql_errno($this->connection), mysql_error($this->connection), __METHOD__, __LINE__);
            return FALSE;
        }
        return mysql_affected_rows($this->connection);
    }

    /**
     * 删除
     * @param $sql
     * @return int 影响行数
     */
    public function delete($sql) {

        if ($this->getConnection() === FALSE) {
            return FALSE;
        }
        if (mysql_query($sql, $this->connection) === FALSE) {
            //TODO
            //$this->error->add(mysql_errno($this->connection), mysql_error($this->connection), __METHOD__, __LINE__);
            return FALSE;
        }
        return mysql_affected_rows($this->connection);
    }

    /**
     * 执行sql
     * @param $sql
     * @return 执行结果
     */
    public function execute($sql) {

        if ($this->getConnection() === FALSE) {
            return FALSE;
        }
        if (($result = mysql_query($sql, $this->connection)) === FALSE) {
            //TODO
            //$this->error->add(mysql_errno($this->connection), mysql_error($this->connection), __METHOD__, __LINE__);
            return FALSE;
        }
        return $result;
    }

    /**
     * 关闭当前db连接
     */
    public function close() {

        if (doom_model_mysqliconnmgr::close($this->connection) === FALSE) {
            //TODO
            //$this->error->add(1, doom_model_mysqliconnmgr::$error, __METHOD__, __LINE__);
            return FALSE;
        }
        $this->connection = NULL;
        return TRUE;
    }

    /**
     * 关闭当前进程所有连接
     */
    static public function closeAll() {

        doom_model_mysqliconnmgr::closeAll();
    }

    public function escapeString($s) {

        return mysql_escape_string($s);
    }

    public function getErrors() {

        return $this->error->getErrorStack();
    }
}
?>
